<template>
  <div class="view-fill">
    <div v-if="!revokeInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        title="消耗明细"
        :btn-list="fullInfo.btnList"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="$permission('consumeOrder:print')"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <el-button
            v-if="
              infoList.data.consumeSourceId === -2 &&
              infoList.data.sourceType !== '79' &&
              $permission('consumeOrder:revokable') &&
              canRevoke
            "
            @click="revokable"
            >撤回</el-button
          >
          <el-button
            v-if="
              infoList.data.consumeSourceId === -2 &&
              $permission('consumeOrder:revoke') &&
              canRevoke
            "
            @click="revoke"
            >无痕撤回</el-button
          >
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <BasicInformation :info="infoList" :labelWidth="labelWidth" />
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <table-container
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :check-box="false"
                :tab-index="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
              >
              </table-container>
            </div>
          </div>
          <individual-details
            v-if="individualInfo.visible"
            :with-surgery="withTable"
            v-model:show-dialog="individualInfo.visible"
            :query="individualInfo.query"
            :info="individualInfo.info"
            :sourceType="infoList.data.sourceType"
            :consume-source-id="infoList.data.consumeSourceId"
            @reset="reset"
            @showRevokable="showRevokable"
          ></individual-details>
        </div>
      </NewFullScreen>
    </div>
    <ConsumeRevoke
      v-if="revokeInfo.visible"
      :ids="revokeInfo.ids"
      v-model:visible="revokeInfo.visible"
      :order-id="revokeInfo.orderId"
      @returnModify="returnModify"
    />
  </div>
</template>

<script setup name="consumeOrderDetail">
import {
  getConsumeOrderDetailCustomizeListAll,
  revokeConsumeOrder,
  detailConsumeOrder,
  exportExcelConsumeOrder,
  getConsumePrint,
} from '@/api/stock.js'
import { getCustomizeSetting } from '@/api/customize'
import { orderAffairAll } from '@/api/affair'
import { fatchTemplateByCode } from '@/api/base'
import ConsumeRevoke from '../consumeRevoke/index'
import IndividualDetails from './IndividualDetails'
import _ from 'lodash'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'id', 'pageType'])

const labelWidth = '120px'
const infoList = ref({
  data: {},
  fieldList: [
    { label: '登记单号', value: 'orderNo', type: 'text' },
    {
      label: '来源消耗单号',
      value: 'consumeSourceOrderNo',
      type: 'text',
    },
    { label: '消耗人', value: 'consumeUserName', type: 'text' },
    { label: '出库部门', value: 'deptName', type: 'text' },
    { label: '出库仓库', value: 'depotName', type: 'text' },
    { label: '消耗部门', value: 'consumeDeptName', type: 'text' },
    { label: '消耗时间', value: 'consumeTime', type: 'text' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'text',
    },
    {
      label: '发票号汇总',
      value: 'receiptNumber',
      type: 'text',
    },
    {
      label: '发票总金额',
      value: 'receiptSumAmount',
      type: 'text',
    },
    { label: '备注', value: 'remark', type: 'popover' },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {},
  },
})
const fullInfo = ref({
  btnList: [
    /*  {
      label: '打印',
      event: print,
      show: proxy.$permission('consumeOrder:print'),
    }, */
    {
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('consumeOrder:exportExcel'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '撤回',
        event: revokeRow,
        show: proxy.$permission('consumeOrder:revokable'),
        ifRender: ifRenderValue,
      },
      {
        label: '个体详情',
        event: showDetail,
        show: proxy.$permission('consumeOrder:IndividualDetails'),
      },
    ],
  },
})
const affairTableInfo = ref({
  api: orderAffairAll,
  query: {
    orderType: 25,
    orderId: props.id,
    sort: 'operate_time desc',
  },
})
const revokeInfo = ref({
  visible: false,
  orderId: '',
  ids: '',
})
const individualInfo = ref({
  visible: false,
  query: {},
  info: {},
})
const withTable = ref(false)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canRevoke = computed(() => {
  let arr = tableInfo.value.data.filter((item) => item.canInvalidCalcQty > 0)
  return arr.length
})

watch(
  () => individualInfo.value.visible,
  (value) => {
    if (!value) {
      getMain()
    }
  }
)

setData()
function setData() {
  let obj = {
    detailConsignConfirmStatusValue: {
      label: '是否寄售',
      value: 'detailConsignConfirmStatusValue',
      asValue: 'detailConsignConfirmStatus',
      componentType: 'select-model',
      code: 'consign_confirm_status',
      show: false,
      hidden: true,
    },
    detailIsConsignBusinessValue: {
      label: '是否寄售',
      value: 'detailIsConsignBusinessValue',
      asValue: 'detailIsConsignBusiness',
      componentType: 'select-model',
      code: 'yes_or_no',
      show: false,
      hidden: true,
    },
    price: {
      label: '单价',
      value: 'price',
      minWidth: '150px',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('consumeOrder:price'),
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('consumeOrder:price'),
      hidden: true,
    },
    orderNo: {
      label: '单号',
      value: 'orderNo',
      componentType: 'input',
      show: false,
      type: 'column',
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      permission: !proxy.$permission('consumeOrder:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
function ifRenderValue(row) {
  return (
    infoList.value.data.consumeSourceId === -2 &&
    row.canInvalidCalcQty > 0 &&
    infoList.value.data.sourceType !== '79'
  )
}
function returnBack() {
  if (proxy.$route.query.returnPath) {
    const view = {
      name: 'consumeOrder',
      path: proxy.$route.path,
    }
    proxy.$store.dispatch('tabsView/delView', view)
    proxy.$router.replace(proxy.$route.query.returnPath)
    return
  }
  emits('returnBack')
}
function reset(val) {
  if (val) {
    getMain()
  }
}
function showDetail(row) {
  let ids
  if (row.groupConcatIds) {
    //未定义表示没有分组条件
    ids = row.groupConcatIds
  } else {
    ids = '' + row.id
  }
  individualInfo.value.info = row
  individualInfo.value.query = {
    id: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: ids,
    },
  }
  individualInfo.value.visible = true
}
function returnModify() {
  getMain()
  getList()
}
function getMain() {
  detailConsumeOrder(props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
      if (!resp.data) {
        showDialog.value = false
        returnBack()
      }
      withTable.value = !!resp.data.withTable
      getList()
    }
  })
}

function getList() {
  getConsumeOrderDetailCustomizeListAll(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.data = resp.data
    }
  })
}
function revokable() {
  //撤回
  revokeInfo.value.orderId = infoList.value.data.id
  revokeInfo.value.ids = ''
  validateRevoke()
}
function revokeRow(row) {
  //撤回
  revokeInfo.value.orderId = infoList.value.data.id
  revokeInfo.value.ids = row.groupConcatIds
  validateRevoke(row)
}
function showRevokable(id) {
  //撤回
  revokeInfo.value.orderId = infoList.value.data.id
  revokeInfo.value.ids = id
  revokeInfo.value.visible = true
}
function validateRevoke(row) {
  getConsumeOrderDetailCustomizeListAll(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data
      if (row && row.id) {
        let item = data.find((item) => item.id === row.id)
        console.log(data)
        if (item.canInvalidCalcQty > 0) {
          revokeInfo.value.visible = true
        } else {
          proxy.$message({
            message: '无可撤回数量，请刷新数据',
            type: 'warning',
            duration: 3500,
            showClose: true,
          })
          return
        }
      } else {
        let arr = data.filter((item) => item.canInvalidCalcQty > 0)
        if (arr.length) {
          revokeInfo.value.visible = true
        } else {
          proxy.$message({
            message: '无可撤回数量，请刷新数据',
            type: 'warning',
            duration: 3500,
            showClose: true,
          })
          return
        }
      }
    }
  })
}
//撤销
function revoke() {
  proxy
    .$confirm('撤回后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      revokeConsumeOrder(props.id).then((resp) => {
        if (resp && resp.success) {
          showDialog.value = false
          returnBack()
        }
      })
    })
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'stockConsumeDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: infoList.value.data.id,
            orderNo: infoList.value.data.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
  /* const consumeSourceOrderNo = infoList.value.data.consumeSourceOrderNo ? 0 : 1
  fatchTemplateByCode({
    resourceCode: 'consumeOrder:print',
    isDefault: consumeSourceOrderNo,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      if (infoList.value.data.consumeSourceOrderNo) {
        temp = proxy.$fn.getPrintTemp(_.find(res.data, ['name', '消耗单撤回']))
      }
      getPirntData(temp)
    }
  }) */
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      orderId: props.id,
      tempCode: 'stockConsumeDetail',
      orderType: 25,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: infoList.value.data.id,
      orderNo: infoList.value.data.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function getPirntData(temp) {
  let params = {
    tableKey:
      'consumeOrderDetail-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO',
    orderIds: [props.id],
  }
  getConsumePrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('consumeOrder:price')
      )
    }
  })
}
//导出excel
function exportExcel() {
  exportExcelConsumeOrder(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function getCustomize() {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey:
      'consumeOrderDetail-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = res.data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      getMain()
    }
  })
}
</script>
